<%@ page pageEncoding="UTF-8"%>
<%@ include file="import.jsp"%>
<%!
	public static final Integer HAS_PUSH = 0;    // 未确认
	public static final Integer CONFIRM = 1;     // 已确认
	public static final Integer ARRIVAL = 3;     // 已到达
	public static final Integer HAS_SEE = 4;     // 已经看过
	public static final Integer NO_ARRIVAL = 5;  // 没法去

	// 创建随访
	public Message createVisit(Map<String, String> parameters, Token token) {
		Message msg = new Message();
		Integer hospital = Tools.getInt(parameters.get("hospital")+"", -9999);
		Integer category = Tools.getInt(parameters.get("category")+"", SURVEY_CATEGORY_FOLLOW);
		String json = parameters.get("survey");
		String check_time = parameters.get("date");
		int doctor_uid = token.getUid();
		String patientUids = parameters.get("patients");
		String send_time = DateUtil.formatDate(new Date());
		String reconfirmed_time = null;
		List quests = null;
		int surveyId = 0;
		if (category == SURVEY_CATEGORY_FOLLOW) {
			reconfirmed_time = DateUtil.formatDate(DateUtil.afterNDay(DateUtil.parseDate(check_time), -2));
			json = Tools.decryptStr(json); // 问卷二次解密
			Map jsonMap = GsonUtil.fromJson(json, new TypeToken<Map>(){});
			quests = (List)jsonMap.get("quests");
			surveyId = Tools.getInt((jsonMap.get("id") + "").replace(".0", ""), surveyId);
		} else {
			surveyId = Tools.getInt((parameters.get("survey_id") + ""), surveyId);
		}
		if (surveyId == 0) {
			setErrcode(msg, FAILURE);
			return msg;
		}
		patientUids = Tools.decryptStr(patientUids); // 病人列表解密
		List patients = GsonUtil.fromJson(patientUids, new TypeToken<List>(){});
		long time = System.currentTimeMillis();
		List<Visit> visits = new ArrayList<Visit>();
		for (int i = 0; i < patients.size(); i++) {
			Map patientMap = (Map)patients.get(i);
			Visit visit = Visit.fromMap(parameters, Visit.class);
			visit.setDoctorUid(doctor_uid);
			visit.setPatientUid(Tools.getInt((patientMap.get("patient_uid") + "").replace(".0", ""), 0));
			visit.setCheckTime(check_time);
			visit.setSendTime(send_time);
			visit.setReconfirmedTime(reconfirmed_time);
			visit.setSurveyId(surveyId);
			visit.setHospital(hospital);
			visit.setIsconfirmed(HAS_PUSH);
			visit.setCancel(0);
			visits.add(visit);
		}
		List<Integer> id_visits = (List<Integer> )DBTools.db("basedb").addItem(visits);
		List<SurveyAnswer> surveyAnswers = new ArrayList<SurveyAnswer>();
		List<Timeline> timelines = new ArrayList<Timeline>();
		List<String> visitNames = QBuilder.db("basedb").queryHql("select title from Survey where id = " + surveyId + " and enable = " + STATUS_ENABLE + " and status = " + STATUS_ENABLE);
		for (int i = 0; i < id_visits.size(); i++) {
			Integer id_visit = id_visits.get(i);
			if (id_visit == null) continue;
			Visit visit = visits.remove(0);
			Timeline timeline = new Timeline();
			timeline.setPatientUid(visit.getPatientUid());
			timeline.setModUid(doctor_uid);
			timeline.setDoctorUid(doctor_uid);
			timeline.setOid(id_visit);
			timeline.setKind(category);
			timeline.setType(visitNames.size() == 0 ? "随访" : visitNames.get(0));
			timeline.setHospital(hospital);
			timeline.setJsonString("{}");
			timeline.setStatus(STATUS_ENABLE);
			timeline.setcTime(System.currentTimeMillis());
			timeline.setDate(DateUtil.formatDate(new Date()));
			timeline.setName(category == SURVEY_CATEGORY_FOLLOW ? "复诊随访" : "问卷随访");
			timelines.add(timeline);
			for (int t = 0; category == SURVEY_CATEGORY_FOLLOW && quests != null && t < quests.size(); t++) {
				Map quest = (Map)quests.get(t);
				int quest_id = Tools.getInt((quest.get("quest_id") + "").replace(".0", ""), 0);
				int type = Tools.getInt((quest.get("type") + "").replace(".0", ""), 0);
				List options = (List)quest.get("options");
				for (int j = 0; options != null && j < options.size(); j++) {
					quest = (Map)options.get(j);
					SurveyAnswer surveyAnswer = new SurveyAnswer();
					surveyAnswer.setSurveyId(surveyId);
					surveyAnswer.setQuestId(quest_id);
					surveyAnswer.setDoctorUid(doctor_uid);
					surveyAnswer.setContent(Tools.getDesc(quest.get("content") + "", ""));
					surveyAnswer.setHospital(hospital);
					surveyAnswer.setcTime(time);
					surveyAnswer.setUid(visit.getPatientUid());
					surveyAnswer.setScore(Tools.getInt(quest.get("score") + "", 0));
					surveyAnswer.setVisitId(id_visit);
					surveyAnswer.setType(type);
					surveyAnswers.add(surveyAnswer);
				}
			}
		}
		if (category == SURVEY_CATEGORY_FOLLOW) {
			DBTools.db("basedb").addItem(surveyAnswers);
		}
		DBTools.db("basedb").addItem(timelines);
		msg.put("visit_id", id_visits);
		return msg;
	}

	// 填写问卷随访
	public Message completeVisit(Map<String, String> parameters, Token token) {
		Message msg = new Message();
		Integer hospital = Tools.getInt(parameters.get("hospital")+"", -9999);
		String json = parameters.get("survey");
		Integer doctorUid = Tools.getInt(parameters.get("doctor_uid")+"", -9999);
		Integer visitId = Tools.getInt(parameters.get("visit_id")+"", -9999);
		json = Tools.decryptStr(json); // 问卷二次解密
		Map jsonMap = GsonUtil.fromJson(json, new TypeToken<Map>(){});
		List quests = (List)jsonMap.get("quests");
		int surveyId = Tools.getInt((jsonMap.get("id") + "").replace(".0", ""), 0);
		long time = System.currentTimeMillis();
		List<SurveyAnswer> surveyAnswers = new ArrayList<SurveyAnswer>();
		int sumScore = 0;
		for (int t = 0; quests != null && t < quests.size(); t++) {
			Map quest = (Map)quests.get(t);
			int quest_id = Tools.getInt((quest.get("quest_id") + "").replace(".0", ""), 0);
			int type = Tools.getInt((quest.get("type") + "").replace(".0", ""), 0);
			List options = (List)quest.get("options");
			for (int j = 0; options != null && j < options.size(); j++) {
				quest = (Map)options.get(j);
				SurveyAnswer surveyAnswer = new SurveyAnswer();
				surveyAnswer.setSurveyId(surveyId);
				surveyAnswer.setQuestId(quest_id);
				surveyAnswer.setDoctorUid(doctorUid);
				surveyAnswer.setContent(Tools.getDesc(quest.get("content") + "", ""));
				surveyAnswer.setHospital(hospital);
				surveyAnswer.setcTime(time);
				surveyAnswer.setUid(token.getUid());
				surveyAnswer.setScore(Tools.getInt(quest.get("score") + "", 0));
				sumScore += surveyAnswer.getScore();
				surveyAnswer.setVisitId(visitId);
				surveyAnswer.setType(type);
				surveyAnswers.add(surveyAnswer);
			}
		}
		List<Visit> visits = QBuilder.db("basedb").queryHql("from Visit where id = " + visitId);
		if (visits.size() > 0) {
			Visit v = visits.get(0);
			v.setScore(sumScore);
			v.setIsconfirmed(ARRIVAL);
			v.setReconfirmedTime(DateUtil.formatDate(new Date()));
			DBTools.db("basedb").modItem(v, v.getId());
		}
		DBTools.db("basedb").addItem(surveyAnswers);
		return msg;
	}

	// 查询随访模板
	public Message queryTemple(Map<String, String> parameters) {
		Message msg = new Message();
		String dept_id = parameters.get("dept_id");
		List<Survey> list = new ArrayList<Survey>();
		if (dept_id == null) {
		  list = QBuilder.db("basedb").queryHql("select new map(id as survey_id, title as survey_title) from Survey where hospital = " + parameters.get("hospital") + " and category = " + parameters.get("category") + " and enable = " + STATUS_ENABLE + " and status = " + STATUS_ENABLE + " and deptId is NUll");
		 } else {
			 list = QBuilder.db("basedb").queryHql("select new map(id as survey_id, title as survey_title) from Survey where hospital = " + parameters.get("hospital") + " and category = " + parameters.get("category") + " and enable = " + STATUS_ENABLE + " and status = " + STATUS_ENABLE + " and deptId = " + dept_id);
		 }
		if (list.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg;
		}
		msg.put("surveys", list);
		return msg;
	}

	// 修改随访
	public Message modifyVisit(Map<String, String> parameters, Token token) {
		Message msg = new Message();
		Visit visit = Visit.fromMap(parameters, Visit.class);
		Visit v = (Visit)queryItem(visit);
		if (v == null) {
			setErrcode(msg, NO_RESULT);
			return msg;
		}

		Integer cancel = Tools.getInt(v.getCancel() + "", 0);
		String operate = "";
		if (visit.getIsconfirmed() == CONFIRM) {
		    // 确认
			operate += "sure";
		}
		if ((visit.getIsconfirmed() == HAS_PUSH && v.getIsconfirmed() == CONFIRM) && (visit.getIsconfirmed() == NO_ARRIVAL && v.getIsconfirmed() == CONFIRM)) {
		    // 取消确认
			cancel ++;
			operate += "cancel";
		}
		visit.setCancel(cancel);
		DBTools.db("basedb").modItem(visit, v.getId());
		msg.put("operate", operate);
		return msg;
	}

	// 查询随访
	public Message queryVisits(Map<String, String> parameters, Token token) {
		Message msg = new Message();
		Visit visit = Visit.fromMap(parameters, Visit.class);
		visit.setDoctorUid(token.getUid());
		String orderBy = (visit.getCategory() == SURVEY_CATEGORY_FOLLOW ? " order by v.checkTime desc, v.id desc" : " order by v.sendTime desc, v.id desc");
		String act = parameters.get("act");
		List list = new ArrayList();
		if ("patients".equals(act)) { // 用户端
			list = QBuilder.db("basedb").queryHql("select new map (v.checkTime as check_time, v.reconfirmedTime as reconfirmed_time, v.sendTime as send_time , v.isconfirmed as isconfirmed, v.id as visit_id, us.name as user_name, us.avatar as avatar, v.surveyId as survey_id, (case when v.score is NULL then 0 else v.score end) as score, (case when v.category is NULL then 2 else v.category end) as category, (case when v.cancel is NULL then 0 else v.cancel end) as cancel) from Visit as v, User as us where us.id = v.doctorUid and v.patientUid = " + token.getUid() + " and v.category = " + visit.getCategory() + " and v.hospital =  " + visit.getHospital() + " and us.hospital = " + visit.getHospital() +" and v.status = "+ STATUS_ENABLE +" and us.status = " + STATUS_ENABLE + orderBy);
		} else {     // 医生端
			list = QBuilder.db("basedb").queryHql("select new map (v.checkTime as check_time, v.reconfirmedTime as reconfirmed_time, v.sendTime as send_time , v.isconfirmed as isconfirmed, v.id as visit_id, us.name as user_name, us.phone as phone, us.gender as gender, u.avatar as avatar, v.surveyId as survey_id, (case when v.score is NULL then 0 else v.score end) as score, (case when v.category is NULL then 2 else v.category end) as category, (case when v.cancel is NULL then 0 else v.cancel end) as cancel) from Visit as v, UserProfile as us, User as u where us.uid = v.patientUid and u.id = us.uid and v.doctorUid = " + token.getUid() + " and v.category = " + visit.getCategory() + " and v.hospital =  " + visit.getHospital() + " and us.hospital = " + visit.getHospital() + " and u.hospital = " + visit.getHospital() +" and v.status = "+ STATUS_ENABLE +" and u.status = "+ STATUS_ENABLE +" and us.self = " + SELF + " and us.status = " + STATUS_ENABLE + orderBy);
		}
		if (list.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg;
		}
		if (visit.getCategory() == SURVEY_CATEGORY_FOLLOW) { // 复诊随访取出要随访的内容
			String visitIds = "-1";
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map)list.get(i);
				int visitId = Tools.getInt(map.get("visit_id") + "", -99999);
				if (visitId == -99999) continue;
				visitIds += ("," + visitId);
			}
			List types = QBuilder.db("basedb").queryHql("select new map(so.content as content, sa.visitId as visit_id) from SurveyAnswer as sa, SurveyOptions as so where sa.visitId in (" + visitIds + ") and sa.type = "+ SURVEY_QUESTION_TYPE_MULTI + " and sa.status = " + STATUS_ENABLE + " and sa.hospital = " + visit.getHospital() + " and so.hospital= " + visit.getHospital() + " and so.status = " + STATUS_ENABLE + " and sa.content = so.id");
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map)list.get(i);
				int visitId = Tools.getInt(map.get("visit_id") + "", -99999);
				Iterator<Map> it = types.iterator();
				String typeStr = (String)map.get("type");
				if (typeStr == null)
					typeStr = "";
				while (it.hasNext()) {
					Map type = it.next();
					int typeId = Tools.getInt(type.get("visit_id") + "", -9999);
					if (visitId == typeId) {
						typeStr += (Tools.getDesc(type.get("content") + "", "") + ",");
						it.remove();
					}
				}
				map.put("type", typeStr.length() > 0 ? typeStr.substring(0, typeStr.length() - 1) : typeStr);
			}
		} else { // 问卷随访取出随访的标题
			String surveyIds = "-1";
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map)list.get(i);
				int surveyId = Tools.getInt(map.get("survey_id") + "", -99999);
				if (surveyId == -99999) continue;
				surveyIds += ("," + surveyId);
			}
			List<Survey> types = QBuilder.db("basedb").queryHql("from Survey where id in (" + surveyIds + ") group by id");
			List<SurveyScore> scores = QBuilder.db("basedb").queryHql("from SurveyScore where sid in (" + surveyIds + ")");
			for (int i = 0; i < list.size(); i++) {
				Map map = (Map)list.get(i);
				int surveyId = Tools.getInt(map.get("survey_id") + "", -99999);
				int score = Tools.getInt(map.get("score") + "", 0);
				for (int j = 0; j < types.size(); j++) {
					Survey survey = types.get(j);
					if (surveyId == survey.getId()) {
						map.put("type", survey.getTitle());
						break;
					}
				}
				for (int j = 0; j < scores.size(); j++) {
					SurveyScore surveyScore = scores.get(j);
					if (surveyId == surveyScore.getSid() && score >= surveyScore.getMin() && score <= surveyScore.getMax()) {
						map.put("content", surveyScore.getContent());
						break;
					}
				}
			}
		}
		msg.put("visits", list);
		return msg;
	}

	// 查询详细
	public Message queryVisitDetail(Map<String, String> parameters, boolean all) {
		Message msg = new Message();
		Visit visit = Visit.fromMap(parameters, Visit.class);
		all = (visit.getCategory() == SURVEY_CATEGORY_QUESTION);
		List<Visit> list = QBuilder.db("basedb").queryHql("from Visit where id = " + visit.getId());
		if (list.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg;
		}
		Visit v = list.get(0);
		Map<String, Object> surveyMap = new HashMap<String, Object>();
		int surveyId = v.getSurveyId();
		int visitId = v.getId();
		List<Survey> surveys = QBuilder.db("basedb").queryHql("from Survey where id = " + surveyId);

		Survey survey = surveys.get(0);
		String title = survey.getTitle();
		String date = v.getCheckTime();
		int id = survey.getId();
		surveyMap.put("title", title);
		surveyMap.put("id", id);
		surveyMap.put("date", date);
		surveyMap.put("isconfirmed", v.getIsconfirmed());
		// 查询副标题
		List<SurveyQuestion> questList = QBuilder.db("basedb").queryHql("from SurveyQuestion where status = " + STATUS_ENABLE + " and surveyId = "+ id + " order by showOrder asc");
		Iterator<SurveyQuestion> it = questList.iterator();
		List<SurveyQuestion> titles = new ArrayList<SurveyQuestion>();
		List<SurveyQuestion> mulInputs = new ArrayList<SurveyQuestion>();
		String questIds = "-1";
		while (it.hasNext()) {
			SurveyQuestion sq = it.next();
			if (sq.getType() == SURVEY_QUESTION_TYPE_PARENT) {
				// 副标题
				titles.add(sq);
				it.remove();
			} else if (sq.getType() == SURVEY_QUESTION_TYPE_MUTILINPUT) {
				// 多重填空的题目
				mulInputs.add(sq);
				it.remove();
			} else {
				// 问题
				questIds += ("," + sq.getId());
			}
		}
		// 根据问题id查出问题选项
		Map<Integer, List<Map<String, Object>>> questIdMap = new HashMap<Integer, List<Map<String, Object>>>(); // 问题和问题选项集合
		List<SurveyOptions> optionList = QBuilder.db("basedb").queryHql("from SurveyOptions where status = " + STATUS_ENABLE + " and questId in(" + questIds + ") order by showOrder asc");
		// 查出病人的答案
		List<SurveyAnswer> answerList = QBuilder.db("basedb").queryHql("from SurveyAnswer where status = " + STATUS_ENABLE + " and questId in(" + questIds + ") and visitId = " + visitId + " and surveyId = " + surveyId);
		for (int i = 0; i < optionList.size(); i++) {
			SurveyOptions option = optionList.get(i);
			String content = option.getContent();
			Integer optionId = option.getId();
			Integer questId = option.getQuestId();
			List<Map<String, Object>> options = questIdMap.get(questId);
			if (null == options) {
				options = new ArrayList<Map<String, Object>>();
			}
			Map<String, Object> anOption = new HashMap<String, Object>();
			anOption.put("content", content);
			anOption.put("option_id", optionId);
			Iterator<SurveyAnswer> itor = answerList.iterator();
			while (itor.hasNext()) {
				SurveyAnswer sa = itor.next();
				int type = sa.getType();
				Integer quest_id = sa.getQuestId();
				if (questId != null && questId.equals(quest_id)) {
					if (type == SURVEY_QUESTION_TYPE_INPUT) { // 填空题
						anOption.put("answer", sa.getContent());
						itor.remove();
					} else if (type == SURVEY_QUESTION_TYPE_MULTI || type == SURVEY_QUESTION_TYPE_SINGLE) {
						Integer option_id = Tools.getInt(sa.getContent(), -99999);
						if (option_id.equals(optionId)) {
							anOption.put("answer", "1");
							itor.remove();
						}
					}
				}
			}
			if (all) {
				options.add(anOption);
				questIdMap.put(questId, options);
			} else {
				if (anOption.get("answer") != null) {
					options.add(anOption);
					questIdMap.put(questId, options);
				}
			}
		}
		// 问题选项加到对应的问题中
		LinkedList<Map<String, Object>> quests = new LinkedList<Map<String, Object>>(); // 问题列表
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion quest = questList.get(i);
			String questTitle = quest.getTitle();
			Integer questId = quest.getId();
			Integer type = quest.getType();
			Integer parentId = quest.getParentId();
			Integer necessary = quest.getNecessary();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			if (type == SURVEY_QUESTION_TYPE_MULTI || type == SURVEY_QUESTION_TYPE_SINGLE) {
				List<Map<String, Object>> tempList = questIdMap.get(questId);
				for (int j = 0; tempList != null && j < tempList.size(); j++) {
					Map<String, Object> tempMap = tempList.get(j);
					if (tempMap.get("answer") == null) {
						tempMap.put("answer", "0");
					}
				}
			}
			aQuest.put("options", questIdMap.get(questId));
			aQuest.put("parent_id", parentId);
			aQuest.put("necessary", necessary);
			aQuest.put("show_order", quest.getShowOrder());
			quests.add(aQuest);
		}
		// 把多重填空子题目放入大标题中
		LinkedList<Map<String, Object>> dest = new LinkedList<Map<String, Object>>();
		dest.addAll(quests);
		for (int i = 0; i < mulInputs.size(); i++) {
			SurveyQuestion sq = mulInputs.get(i);
			String questTitle = sq.getTitle();
			Integer questId = sq.getId();
			Integer type = sq.getType();
			Integer parentId = sq.getParentId();
			Integer necessary = sq.getNecessary();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("parent_id", parentId);
			aQuest.put("necessary", necessary);
			aQuest.put("show_order", sq.getShowOrder());
			dest.addFirst(aQuest);
			Iterator<Map<String, Object>> itor = quests.iterator();
			while (itor.hasNext()) {
				Map<String, Object> map = itor.next();
				Integer sqId = (Integer)map.get("parent_id");
				if (questId.equals(sqId)) {
					List<Map<String, Object>> childList = (List<Map<String, Object>>)aQuest.get("multils");
					if (childList == null) {
						childList = new ArrayList<Map<String, Object>>();
						aQuest.put("multils", childList);
					}
					childList.add(map);
					itor.remove();
					dest.remove(map);
				}
			}
		}
		// 根据showorder排序
		quests.clear();
		quests.addAll(dest);
		Collections.sort(quests, new Comparator<Map<String, Object>>() {

			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				return Tools.getInt(o1.get("show_order") + "", 0).compareTo(Tools.getInt(o2.get("show_order")+"", 0));
			}
		});

		// 问题加入大分类
		dest.clear();
		dest.addAll(quests);
		for (int i = 0; i < titles.size(); i++) {
			SurveyQuestion sq = titles.get(i);
			String questTitle = sq.getTitle();
			Integer questId = sq.getId();
			Integer type = sq.getType();
			Integer parentId = sq.getParentId();
			Integer necessary = sq.getNecessary();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("parent_id", parentId);
			aQuest.put("necessary", necessary);
			aQuest.put("show_order", sq.getShowOrder());
			dest.addFirst(aQuest);
			Iterator<Map<String, Object>> itor = quests.iterator();
			while (itor.hasNext()) {
				Map<String, Object> map = itor.next();
				Integer sqId = (Integer)map.get("parent_id");
				if (questId.equals(sqId)) {
					List<Map<String, Object>> childList = (List<Map<String, Object>>)aQuest.get("quests");
					if (childList == null) {
						childList = new ArrayList<Map<String, Object>>();
						aQuest.put("quests", childList);
					}
					childList.add(map);
					itor.remove();
					dest.remove(map);
				}
			}
		}
		Collections.sort(dest,new Comparator<Map>(){
      public int compare(Map map1,Map map2){// 定义逆序排序规则 从小到大排序
        if ( Tools.getInt(map1.get("show_order") + "", 0).compareTo(Tools.getInt(map2.get("show_order") + "", 0)) > 0) {
          return 1;
        }
        if (Tools.getInt(map1.get("show_order") + "", 0).equals(Tools.getInt(map2.get("show_order") + "", 0))) {
          return 0;
        }
        return -1;
      }
    });
		surveyMap.put("quests", dest);
		msg.put("survey", surveyMap);
		return msg;
	}


	// 查询随访下的联系人
	public Message contact(Map<String, String> parameters, Token token) {
		Message msg = new Message();
		DoctorGroup doctorGroup = DoctorGroup.fromMap(parameters, DoctorGroup.class);
		doctorGroup.setDoctorUid(token.getUid());
		List list = QBuilder.db("basedb").select("new map(dg.id as group_id, dg.groupName as group_name, dg.doctorUid as doctor_uid, count(gp.id) as num)").from("DoctorGroup as dg, GroupPatient as gp").where(new Where("dg.id = gp.groupId").and("dg.doctorUid = ",doctorGroup.getDoctorUid()).and("dg.status = ", STATUS_ENABLE).and("gp.status = ", STATUS_ENABLE).and("dg.hospital = ", doctorGroup.getHospital()).and("gp.hospital = ", doctorGroup.getHospital())).group("gp.groupId").query().getResultObj();
		String groupIds = "-9";
		for (int i = 0; i < list.size(); i ++) {
			Map dg = (Map)list.get(i);
			int id = Tools.getInt(dg.get("group_id") + "");
			groupIds += ("," + id);
		}
		List patients = QBuilder.db("basedb").select("new map(gp.groupId as group_id, gp.patientUid as patient_uid , gp.id as g_patient_id, u.name as patient_name, u.age as age, u.gender as gender, u.medicalType as medical_type, u.phone as phone, user.avatar as avatar)").from("GroupPatient as gp, UserProfile as u, User as user").where(new Where("gp.patientUid = u.uid").and("gp.status = ", STATUS_ENABLE).and("u.status = ", STATUS_ENABLE).and("gp.hospital = ", doctorGroup.getHospital()).and("gp.patientUid = user.id").and("u.hospital = ", doctorGroup.getHospital()).and("u.self=0").and("gp.groupId in (" +groupIds+ ")")).query().getResultObj();
		for (int i = 0; i < list.size(); i++) {
			Map group = (Map)list.get(i);
			int id = Tools.getInt(group.get("group_id") + "");
			List contacts = (List)group.get("contact");
			if (contacts == null)
				contacts = new ArrayList();
			group.put("contact", contacts);
			for (int j = 0; j < patients.size(); j ++) {
				Map patient = (Map)patients.get(j);
				if (id == Tools.getInt(patient.get("group_id") + "")) {
					contacts.add(patient);
				}
			}
		}
		msg.put("contacts", list);
		return msg;
	}
%>
